/*-
 * <<
 * sag
 * ==
 * Copyright (C) 2019 sia
 * ==
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * >>
 */


package com.creditease.gateway.message.config;

import com.creditease.gateway.message.api.BaseMqProducer;
import com.creditease.gateway.message.api.impl.KafkaProducer;
import com.creditease.gateway.message.appender.SagAppenderRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @Author: yongbiao
 * @Date: 2019-06-05 18:02
 */
@EnableConfigurationProperties(SagMqProperties.class)
@ConditionalOnMissingBean(ProducerAutoConfiguration.class)
public class ProducerAutoConfiguration {

    @Autowired
    private SagMqProperties properties;

    @Bean
    @ConditionalOnMissingBean(BaseMqProducer.class)
    public BaseMqProducer getMqProducer() {

        if (properties.getMqType() == SagMqProperties.MqType.Kafka) {
            KafkaProducer producer = new KafkaProducer();
            producer.setTopicPrefix(properties.getKafka().getTopicPrefix());
            producer.setNumOfPartition(properties.getKafka().getProducer().getNumOfPartition());
            producer.start();

            return producer;
        }

        return null;
    }

    @Bean
    @ConditionalOnMissingBean(SagAppenderRunner.class)
    public SagAppenderRunner getAppenderRunner() {

        if(properties.getAppender().getRunnerEnable()) {
            return new SagAppenderRunner();
        }

        return null;
    }
}
